﻿using System;
using System.Collections.Generic;
using System.Linq;
using yiCommerce.Core;
using yiCommerce.Core.Data;
using yiCommerce.Core.Domain.Products;

namespace yiCommerce.Service.Products
{
    public class ProductSearchService:IProductSearchService
    {
        private IRepository<Product> _productRepository;


        public ProductSearchService(IRepository<Product> productRepository)
        {
            _productRepository = productRepository;
        }

        public IList<Product> SearchProducts(int shopId, int categoryId, int brandId, string searchProductName, ProductSortingEnum sortingEnum, int pageIndex,
                                         int pageSize)
        {
            var query = _productRepository.Table;
            query = query.Where(p => !p.Deleted);
            //query = query.Where(p => p.Published);

            //searching by searchProductName
            if (!String.IsNullOrWhiteSpace(searchProductName))
            {
                query = from p in query
                        from pv in p.ProductVariants.DefaultIfEmpty()
                        where p.ProductName.Contains(searchProductName) ||

                              (pv.Name.Contains(searchProductName))
                        select p;

            }
            //shop filtering
            if (shopId != 0)
            {
                //search in shop 
                query = from p in query
                        where p.ShopId == shopId
                        select p;
            }

            //category filtering
            if (categoryId !=0)
            {
                //search in subcategories
                query = from p in query
                        from pc in p.ProductCategories.Where(pc => categoryId== pc.CategoryId)
                        select p;
            }


            //brandId filtering
            if (brandId > 0)
            {
                query = from p in query
                        from pm in p.ProductBrands.Where(pm => pm.BrandId== brandId)
                        select p;

            }

            if (sortingEnum == ProductSortingEnum.CreatedOn)
            {
                
                query = from p in query
                    orderby p.CreatedOnUtc descending
                    select p;

            }
            var products = new PagedList<Product>(query, pageIndex, pageSize);

            if (products != null)
            {
                return ProductMapper.ToProducts(products);
            }
            return products;
        }
    }
}